﻿using DataTier;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace KlageSystem
{
    public partial class Mail : System.Web.UI.Page
    {
        Data_Klagebrev klageBrev = null;
        string connStr = ConnectionManager.GetConnStr();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int id;
                if (!int.TryParse(Request.Params.Get("id"), out id))
                {
                    Response.Redirect("~/Default.aspx");
                    return;
                }
                klageBrev = Data_Klagebrev.Load(connStr, id);
                ViewState["klageBrev"] = klageBrev;
            }
            else
            {
                klageBrev = (Data_Klagebrev)ViewState["klageBrev"];
            }

            txtEmail.Text = klageBrev.ToHTMLString(connStr);

            var orgKlagebrev = Org_Klagedata.Load(connStr, klageBrev.OrgKlagenr);
            btnSend.Enabled = (orgKlagebrev.Status != KlageStatus.Afsendt || Session["user"].ToString() == "Administrator");
            btnSend.ToolTip = (orgKlagebrev.Status != KlageStatus.Afsendt) ? "Send brevet" : "Kan ikke sende, da klagen allerede er afsendt";
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            var addr = new Dictionary<string, string>();
            addr.Add("toAddr", Properties.Settings.Default.MailToAddress);
            addr.Add("toName", Properties.Settings.Default.MailToName);
            addr.Add("ccAddr", Properties.Settings.Default.MailCCAddress);
            addr.Add("ccName", Properties.Settings.Default.MailCCName);

            var handler = new MailHandler();
            handler.SendMail(hiddenText.Value, klageBrev.GetSubjet(connStr), Server.MapPath("~/"), addr, klageBrev.Billeder);
            var orgKlage = Org_Klagedata.Load(connStr, klageBrev.OrgKlagenr);
            orgKlage.Status = KlageStatus.Afsendt;
            orgKlage.Save(connStr);
            ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.opener.document.location.href('Default.aspx');self.close();", true);

        }

        protected void btnLuk_Click(object sender, EventArgs e)
        {
            ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
        }

        private void closeWindow()
        {
            ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
        }
    }
}